package com.prj.ufdm.demo.tutorial.thread;
/**
 *  通过线程的  wait、notity 方法，实现两个线程交替打印
 * @author Administrator
 */
public class TestWaitNotify {

	public static void main(String[] args) {
		// 线程共同访问的对象（synchronized 通过锁定共同对象实现同步）
		Object lock = new Object();
		new Thread(new TwnThreadA(lock)).start();
		new Thread(new TwnThreadB(lock)).start();
	}

}

class TwnThreadA implements Runnable {
	Object lock;
	TwnThreadA(Object lock){
		super();
		this.lock = lock;
	}
	@Override
	public void run() {
		try {
			synchronized(lock) {
				while(true) {
					System.out.println("线程A：运行");
					lock.notify();
					System.out.println("线程A：唤醒B");
					System.out.println("线程A：休眠");
					lock.wait();
					Thread.sleep(2000);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class TwnThreadB implements Runnable{
	Object lock;
	TwnThreadB(Object lock){
		super();
		this.lock = lock;
	}
	
	@Override
	public void run() {
		try {
			synchronized(lock) {
				while(true) {
					System.out.println("线程B：运行");
					lock.notify();
					System.out.println("线程B：唤醒A");
					System.out.println("线程B：休眠");
					lock.wait();
					Thread.sleep(2000);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
